package com.alks.function.service.impl.procurement;


import com.alibaba.excel.util.StringUtils;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.procurement.*;
import com.alks.function.data.request.procurement.PackagMaterialRequest;
import com.alks.function.data.request.procurement.PcPackStyleTypeMtlRequest;
import com.alks.function.data.request.procurement.SdMaterialRequest;
import com.alks.function.mapper.SdStyleMapper;
import com.alks.function.mapper.procurement.BrandMaterialDefinitionMapper;
import com.alks.function.mapper.procurement.PackagMaterialDefinitionMapper;
import com.alks.function.service.procurement.BrandMaterialDefinitionService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BrandMaterialDefinitionServiceImpl implements BrandMaterialDefinitionService {

    @Autowired
    private BrandMaterialDefinitionMapper brandMaterialDefinitionMapper;

    @Autowired
    private PackagMaterialDefinitionMapper packagMaterialDefinitionMapper;

    @Autowired
    private  RedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SdStyleMapper sdStyleMapper;


    /*品牌*/
    /**
     * 品牌明细-选择品牌-回显
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getBrandTypeList(String style) {
        String companyId = UserIdThread.get().getCompanyId();
//        List<SdBrandDto> typeList = brandMaterialDefinitionMapper.getBrandTypeList(companyId,style);
        List<SdBrandDto> typeList = sdStyleMapper.getStyleList(companyId);

        //判断品牌
        List<PcPackStyleDto> brandDetailDtoList = brandMaterialDefinitionMapper.getBrandMaterialListByStyle(null,companyId);

        if(ObjectUtils.isNotEmpty(typeList) && ObjectUtils.isNotEmpty(brandDetailDtoList)){
            typeList.forEach(dto -> {
                dto.setFlag(brandDetailDtoList.stream().anyMatch(dto1 -> dto1.getStyle().equals(dto.getStyle())) ? "Y" : "N");
            });
        }
        HashMap map = new HashMap<>();
        map.put("lotNoList", typeList);
        map.put("total", typeList.size());
        return ResponseInfo.ok(map);
    }

    /**
     * 品牌添加
     * @param style
     * @return
     */
    @Override
    public ResponseInfo addBrand(String style) {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();

        //判断品牌
        List<SdBrandDto> typeList = brandMaterialDefinitionMapper.getBrandTypeList(companyId,style);
//        boolean brandExists = typeList.stream().anyMatch(dto -> dto.getStyle().equals(style));
        if (!typeList.isEmpty()) {
            throw new ServiceErrorException("品牌重复添加！");
        }

        int count = brandMaterialDefinitionMapper.addBrand(companyId,userName,style);
        if(count > 0){
            return ResponseInfo.ok("操作成功");
        }else{
            throw new ServiceErrorException("操作失败");
        }
    }

    /*品牌明细*/
    /**
     * 品牌明细：查询
     * @param style
     * @return
     */
    @Override
    public ResponseInfo getBrandMaterialListByStyle(String style) {
        //获取公司
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();

        List<PcPackStyleDto> brandDetailDtoList = brandMaterialDefinitionMapper.getBrandMaterialListByStyle(style,companyId);

        PageInfo list = new PageInfo(brandDetailDtoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", brandDetailDtoList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 品牌明细增加
     * @param style
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo addBrandMaterial(String style) {
        //获取公司
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();
        String userName = sysUserTokenDTO.getUserName();

        //健壮性判断
        if (style==null || companyId==null) {
            throw new ServiceErrorException("参数异常！");
        }
        //判断品牌是否重复
        List<PcPackStyleDto> brandDetailDtoList = brandMaterialDefinitionMapper.getBrandMaterialListByStyle(style,companyId);
        boolean brandExists = brandDetailDtoList.stream().anyMatch(dto -> dto.getStyle().equals(style));
        if (brandExists) {
            throw new ServiceErrorException("品牌重复添加！");
        }
        //史倩待发现 品牌明细增加（不存在的品牌无法添加）
        //不知道品牌表是哪个，暂时自己添加的
//        List<SdBrandDto> typeList = brandMaterialDefinitionMapper.getBrandTypeList(companyId,null);
        List<SdBrandDto> typeList = sdStyleMapper.getStyleList(companyId);
        boolean isStyleExist = typeList.stream().anyMatch(dto -> dto.getStyle() != null && dto.getStyle().equals(style));
        if (!isStyleExist) {
            throw new ServiceErrorException("改品牌不存在！");
        }

        //赋值
        PcPackStyle pcPackStyle = new PcPackStyle();
        pcPackStyle.setCompanyId(companyId);
        pcPackStyle.setStyle(style);
        pcPackStyle.setShipmentId("OMJ");
        pcPackStyle.setShipmentName("OMJ");
        pcPackStyle.setSysUser(userName);
        pcPackStyle.setSysDate(new Date());

        //新增
        int count = brandMaterialDefinitionMapper.addBrandMaterial(pcPackStyle);
        if(count > 0){
            return ResponseInfo.ok("新增成功");
        }else{
            throw new ServiceErrorException("新增失败");
        }
    }

    /**
     * 品牌明细删除
     * @param style
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteBrandMaterial(String style) {
        //获取公司
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();

        //健壮性判断
        if (style == null || companyId == null) {
            throw new ServiceErrorException("参数异常！");
        }
        //查询该品牌是否已存在包材分类明细
        List<PcPackStyleTypeDto> brandDetailDtoList = brandMaterialDefinitionMapper.getPackageMaterialByStyle(style,companyId);
        if(ObjectUtils.isNotEmpty(brandDetailDtoList)){
            throw new ServiceErrorException("该品牌已存在包材分类明细，不能删除!");
        }

        // 删除品牌材料
        int count = brandMaterialDefinitionMapper.deleteBrandMaterial(style, companyId);
        if (count > 0) {
            return ResponseInfo.ok("删除成功");
        }else{
            throw new ServiceErrorException("删除失败");
        }
    }

    /*包材分类明细*/
    /**
     * 选择包材分类查询
     * @param style
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getPackagMaterialList( String style) {
        String companyId = UserIdThread.get().getCompanyId();
        //1.查 选择包材分类里面的数据
        List<PcPackMtlTypeSkcDto> packagMaterialList = packagMaterialDefinitionMapper.getPackagMaterialList(companyId);
        //2.查现在包材分类明细
        List<PcPackStyleTypeDto> brandDetailDtoList = brandMaterialDefinitionMapper.getPackageMaterialByStyle(style,companyId);

        // 检查是否有相同的 seqNo 和 typeName，有的话flag设置为Y
        for (PcPackMtlTypeSkcDto dto : packagMaterialList) {
            if (brandDetailDtoList.stream().anyMatch(item -> item.getSeqNo().equals(dto.getSeqNo()) && item.getTypeName().equals(dto.getTypeName()))) {
                dto.setExistFlag("Y");
            }
        }

        PageInfo list = new PageInfo(packagMaterialList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", packagMaterialList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);

    }

    /**
     * 包材分类明细查询
     * @param style
     * @return
     */
    @Override
    public ResponseInfo getPackageMaterialByStyle(String style) {
        //获取公司
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();

        List<PcPackStyleTypeDto> brandDetailDtoList = brandMaterialDefinitionMapper.getPackageMaterialByStyle(style,companyId);

        //查询所有无材料明细，有的话给颜色标记
        if (ObjectUtils.isNotEmpty(brandDetailDtoList)) {
            for (PcPackStyleTypeDto packDto : brandDetailDtoList) {
                if(ObjectUtils.isNotNull(packDto)&& ObjectUtils.isNotNull(packDto.getSeqNo())){
                    //查询改包材有无材料明细
                    List<PcPackStyleTypeMtlDto> pcPackStyleTypeMtlDtoList = brandMaterialDefinitionMapper.getMaterialList(style, packDto.getTypeName(), companyId, Integer.valueOf(packDto.getSeqNo()));
                    if (ObjectUtils.isNotEmpty(pcPackStyleTypeMtlDtoList)) {
                        packDto.setColorFlag("1");
                    }
                }
            }
        }
        PageInfo list = new PageInfo(brandDetailDtoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", brandDetailDtoList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 包材分类明细：增加
     * @param request
     * @param style
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo addPackagMaterial(List<PackagMaterialRequest> request, String style) {
        //获取公司和用户
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();
        String userName = sysUserTokenDTO.getUserName();
        //健壮性判断
        if (ObjectUtils.isEmpty(request)) {
            throw new ServiceErrorException("参数异常！");
        }
        //创建包材明细数据，可批量添加
        List<PcPackStyleType> brandMaterialList = new ArrayList<>();
        List<PackagMaterialRequest> brandMaterialList2 = new ArrayList<>();
        for (PackagMaterialRequest r : request) {
            //有颜色的编辑,没颜色的添加
            if (ObjectUtils.isNull(r.getExistFlag())){
                PcPackStyleType brandMaterial = new PcPackStyleType();
                //添加所有
                brandMaterial.setCompanyId(companyId);
                brandMaterial.setStyle(style);
                brandMaterial.setShipmentId("OMJ");
                brandMaterial.setShipmentName("OMJ");
                brandMaterial.setSysUser(userName);
                brandMaterial.setSysDate(new Date());
                brandMaterial.setSeqNo(r.getSeqNo());
                brandMaterial.setSizeFlag(r.getSizeFlag());
                brandMaterial.setCaluBase(r.getCaluBase());
                brandMaterial.setTypeName(r.getTypeName());
                brandMaterialList.add(brandMaterial);
            }else{
                //编辑这两个就可以
                r.setCaluBase(r.getCaluBase() ==null ? null : r.getCaluBase());
                r.setSizeFlag(r.getSizeFlag() ==null ? null : r.getSizeFlag());
            }
        }

        int count = 0;
        //批量新增
        if(!brandMaterialList.isEmpty()) {
            count = brandMaterialDefinitionMapper.addPackagMaterial(brandMaterialList);
        }
        if(!brandMaterialList2.isEmpty()){
            count = brandMaterialDefinitionMapper.updateBatchPackagMaterial(brandMaterialList2, companyId,style);
        }
        if (count > 0) {
            return ResponseInfo.ok("分类增加成功!");
        }else{
            return ResponseInfo.ok("分类增加成功!");
        }
    }

    /**
     * 包材分类明细：删除
     * @param request
     * @param style
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo   deletePackagMaterial(PackagMaterialRequest request, String style) {
        //获取公司
        String companyId = UserIdThread.get().getCompanyId();
        //健壮性判断
        if (request == null || style == null || companyId == null) {
            throw new ServiceErrorException("参数异常！");
        }

        //两种情况不能删
        //1.该包材类别已存在物料明细，报错：该包材类别已存在物料明细，不能删除
        List<PcPackStyleTypeMtlDto> pcPackStyleTypeMtlDtoList = brandMaterialDefinitionMapper.getMaterialList(style, request.getTypeName(), companyId,request.getSeqNo());
        if(ObjectUtils.isNotEmpty(pcPackStyleTypeMtlDtoList)){
            throw new ServiceErrorException("该包材类别已存在物料明细，不能删除！");
        }
        //2.todo出错一非本部门分类不能删除
        //史倩待做
        //删除
        brandMaterialDefinitionMapper.deletePackagMaterial(request, style,companyId);
        return ResponseInfo.ok("删除成功");
    }


    /**
     * 包材类别修改
     * @param request
     * @param style
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo updatePackagMaterial(List<PackagMaterialRequest> request, String style) {
        //获取公司
        String companyId = UserIdThread.get().getCompanyId();
        //健壮性判断
        if (ObjectUtils.isEmpty(request) || ObjectUtils.isNull(style)) {
            throw new ServiceErrorException("参数异常！");
        }else{
            for (PackagMaterialRequest materialRequest : request) {
                materialRequest.setCaluBase(materialRequest.getCaluBase() ==null ? null : materialRequest.getCaluBase());
                materialRequest.setSizeFlag(materialRequest.getSizeFlag() ==null ? null : materialRequest.getSizeFlag());
            }
            int count = brandMaterialDefinitionMapper.updateBatchPackagMaterial(request,companyId,style);
            if (count > 0) {
                return ResponseInfo.ok("修改成功");
            }else{
                throw new ServiceErrorException("修改失败");
            }
        }
    }

    /*材料明细*/
    /**
     * 材料明细查询
     * @param style
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getMaterialList(String style, PackagMaterialRequest request) {
        //获取公司
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();

        List<PcPackStyleTypeMtlDto> pcPackStyleTypeMtlDtoList = brandMaterialDefinitionMapper.getMaterialList(style,request.getTypeName(),companyId,request.getSeqNo());

        PageInfo list = new PageInfo(pcPackStyleTypeMtlDtoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", pcPackStyleTypeMtlDtoList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 材料明细删除
     * @param request
     * @param style
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteMaterial(String style, PackagMaterialRequest request, String mtlNo) {
        //获取公司
        SysUserTokenDTO sysUserTokenDTO = UserIdThread.get();
        String companyId = sysUserTokenDTO.getCompanyId();
        //查询改包材分类的所有材料明细
        PcPackStyleTypeMtl MaterialDetail = brandMaterialDefinitionMapper.getMaterialByMtlNo(style,companyId,mtlNo,request.getSeqNo(),request.getTypeName());
        // 删除品牌材料
        brandMaterialDefinitionMapper.deleteMaterial(MaterialDetail);
        return ResponseInfo.ok("删除成功");

    }

    /**
     * 选择材料=材料明细：新增
     * @return
     */
    @Override
    public ResponseInfo addMaterialDetail(PcPackStyleTypeMtlRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        PcPackStyleTypeMtl mtl = new PcPackStyleTypeMtl();
        if(ObjectUtils.isNotEmpty(request)){
            mtl.setCompanyId(companyId);
            mtl.setShipmentId("OMJ");
            mtl.setShipmentName("OMJ");
            mtl.setStyle(request.getStyle());
            mtl.setSeqNo(request.getSeqNo());
            mtl.setMtlNo(request.getMtlNo());
            mtl.setTypeName(request.getTypeName());
            mtl.setMtlName(request.getMtlName());
            mtl.setMtlColor(request.getMtlColor());
            mtl.setMtlSpec(request.getMtlSpec());
            mtl.setMtlUnit(request.getMtlUnit());
            mtl.setUsage(request.getUsage());
            mtl.setSize1(request.getSize1());
            mtl.setSize2(request.getSize2());
            mtl.setSysDate(new Date());
            mtl.setSysUser(userName);
            mtl.setPackType(request.getPackType());
        }
        int count = brandMaterialDefinitionMapper.addgetMaterialByMtlNo(mtl);
        if (count > 0) {
            return ResponseInfo.ok("操作成功");
        }else{
            throw new ServiceErrorException("操作失败");
        }
    }

    /**
     * 选择包材材料中挑到装箱方式后确认:添加到材料明细
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo addBatchMaterialDetail(List<PcPackStyleTypeMtlRequest> request) {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        if(ObjectUtils.isNotEmpty(request)){
            //
            //查询该品牌的所有mtlNo，有重复的不会添加
            List<PcPackStyleTypeMtlDto> materialList = brandMaterialDefinitionMapper.getAllMaterialList(request.get(0).getStyle(),companyId);
            List<String> mtlList = materialList.stream().map(PcPackStyleTypeMtlDto::getMtlNo)
                    .collect(Collectors.toList());

            List<PcPackStyleTypeMtl> mtls = new ArrayList<>();
            for (PcPackStyleTypeMtlRequest r : request) {
                if (!mtlList.contains(r.getMtlNo())) { // 检查 mtlNo 是否在 mtlList 中
                    PcPackStyleTypeMtl mtl = new PcPackStyleTypeMtl();
                    //如果MtlNo在本品牌有相似的，不会添加
                    mtl.setCompanyId(companyId);
                    mtl.setShipmentId("OMJ");
                    mtl.setShipmentName("OMJ");
                    mtl.setStyle(r.getStyle());
                    mtl.setSeqNo(r.getSeqNo());
                    mtl.setMtlNo(r.getMtlNo());
                    mtl.setTypeName(r.getTypeName());
                    mtl.setMtlName(r.getMtlName());
                    mtl.setMtlColor(r.getMtlColor());
                    mtl.setMtlSpec(r.getMtlSpec());
                    mtl.setMtlUnit(r.getMtlUnit());
                    mtl.setUsage(1);
                    mtl.setSysDate(new Date());
                    mtl.setSysUser(userName);
                    mtl.setPackType(r.getPackType());
                    mtls.add(mtl);
                }
            }
            // 判断 mtls 是否为空，为空则直接返回错误信息
            if (mtls.isEmpty()) {
                throw new ServiceErrorException("所有物料都已存在于该材料明细中！");
            }

            int count = brandMaterialDefinitionMapper.addBatchMaterialDetail(mtls);
            if (count > 0) {
                return ResponseInfo.ok("操作成功");
            } else {
                throw new ServiceErrorException("操作失败");
            }

        }else{
            throw new ServiceErrorException("请选择物料资料！");
        }
    }

    /**
     * 材料明细：编辑（用量（比））
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updateMaterialDetail(PcPackStyleTypeMtlRequest request) {

        if(ObjectUtils.isNotEmpty(request)){
            String companyId = UserIdThread.get().getCompanyId();
            PcPackStyleTypeMtl mtl = new PcPackStyleTypeMtl();
            BeanUtils.copyProperties(request,mtl);
            mtl.setCompanyId(companyId);
            mtl.setUsage(request.getUsage());
            //史倩待完成 判断条件
            mtl.setSize1(request.getSize1());
            mtl.setSize2(request.getSize2());
            int count = brandMaterialDefinitionMapper.updateMaterialDetail(mtl);
            if (count > 0) {
                return ResponseInfo.ok("操作成功");
            }else{
                throw new ServiceErrorException("操作失败");
            }
        }else{
            throw new ServiceErrorException("参数异常");
        }
    }

    /*定义装箱方式*/
    /**
     * 定义装箱方式
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo addBoxingStyle(List<PcPackTypeDto> request) {
        String companyId = UserIdThread.get().getCompanyId();
        ArrayList<PcPackType> pcPackTypes = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(request)){
            for (PcPackTypeDto pcPackTypeDto : request) {
                PcPackType pcPackType = new PcPackType();
                if (pcPackTypeDto!=null) {
                    pcPackType.setCompanyId(companyId);
                    pcPackType.setSeqNo(pcPackTypeDto.getSeqNo());
                    pcPackType.setCaseQty(pcPackTypeDto.getCaseQty());
                    pcPackType.setPackType(pcPackTypeDto.getPackType());
                    pcPackTypes.add(pcPackType);
                }
            }
        }
        brandMaterialDefinitionMapper.addBoxingStyle(pcPackTypes);
        return ResponseInfo.ok("操作成功");
    }

    /**
     * 查询装箱方式
     * @return
     */
    @Override
    public ResponseInfo getBoxingStyle() {
        String companyId = UserIdThread.get().getCompanyId();
        List<PcPackTypeDto> boxingStyleList = brandMaterialDefinitionMapper.getBoxingStyle(companyId);

        PageInfo list = new PageInfo(boxingStyleList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", boxingStyleList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /*物料建档*/
    /**
     * 物料资料建档:查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getMaterialDataFilingList(SdMaterialRequest request) {
        //史倩待完成 有个查询条件位置
        //添加指令查询条件
        String companyId = UserIdThread.get().getCompanyId();
        List<SdMaterialDto> sdMaterialDtoList = brandMaterialDefinitionMapper.getMaterialDataFilingList(companyId, request);

        PageInfo list = new PageInfo(sdMaterialDtoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", sdMaterialDtoList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 物料资料建档:生成物料编号
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo makeSdMaterial(SdMaterialRequest request) {
        if (StringUtils.isBlank(request.getMtlType()) || StringUtils.isBlank(request.getMtlName()) || StringUtils.isBlank(request.getMtlUnit())) {
            throw new ServiceErrorException("数据不完整！分类、材料名称和单位不能为空！");
        }

        //物料编码已存在
        if(!StringUtils.isBlank(request.getMtlNo())){
            throw new ServiceErrorException("页面上的存在物料编码，请检查！");
        }

        //上锁
        String companyId = UserIdThread.get().getCompanyId();
        String lockKey = "makeSdMaterial:" + companyId + request.getMtlType();
        String lockValue = UUID.randomUUID().toString();
        Boolean isLocked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
        if (!isLocked) {
            throw new ServiceErrorException("系统处理数据中,请稍后重试!");
        }
        try {

        //有一个判断，判断材料是否已经存在
        List<SdMaterialDto> sdMaterialDtoList = brandMaterialDefinitionMapper.getMaterialDataFilingList(companyId, request);
        if(ObjectUtils.isNotEmpty(sdMaterialDtoList)){
            throw new ServiceErrorException("该材料已存在!");
        }

        SdMaterial sdMaterial = new SdMaterial();
        BeanUtils.copyProperties(request,sdMaterial);
        //生成物料编号
            // 1. 从数据库中获取当前最大编号
            SdMaterialDto materialData = brandMaterialDefinitionMapper.getMaterialMaxData(companyId, request.getMtlType());

            String newCode = generateNewCode(request.getMtlType(), 5, (materialData != null && materialData.getMtlNo() != null ? materialData.getMtlNo() : null));
            sdMaterial.setMtlNo(newCode);
            return ResponseInfo.ok(sdMaterial);

        } finally {
            // 检查并释放锁
            String existingValue = (String) redisTemplate.opsForValue().get(lockKey);
            if (lockValue.equals(existingValue)) {
                redisTemplate.delete(lockKey); // 释放锁
            }
        }
    }

    /**
     * 物料资料建档：增加
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo addSdMaterial(SdMaterialRequest request) {
        if(StringUtils.isBlank(request.getMtlType()) || StringUtils.isBlank(request.getMtlName()) || StringUtils.isBlank(request.getMtlUnit())){
            throw new ServiceErrorException("数据不完整！分类、材料名称和单位!");
        }

        //上锁
        String companyId = UserIdThread.get().getCompanyId();
        String lockKey = "makeSdMaterial:" + companyId + request.getMtlType();
        String lockValue = UUID.randomUUID().toString();
        Boolean isLocked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
        if (!isLocked) {
            throw new ServiceErrorException("系统处理数据中,请稍后重试!");
        }
        try {
        //有一个判断，判断材料是否已经存在
        List<SdMaterialDto> sdMaterialDtoList = brandMaterialDefinitionMapper.getMaterialDataFilingList(companyId, request);
        if(ObjectUtils.isNotEmpty(sdMaterialDtoList)){
            throw new ServiceErrorException("该材料已存在!");
        }
        SdMaterial sdMaterial = new SdMaterial();
        sdMaterial.setMtlNo(request.getMtlNo());
        sdMaterial.setCompanyId(companyId);
        sdMaterial.setMtlType(request.getMtlType() != "" ? request.getMtlType() : null);
        sdMaterial.setMtlName(request.getMtlName() != "" ? request.getMtlName() : null);
        sdMaterial.setMtlSpec(request.getMtlSpec() != "" ? request.getMtlSpec() : null);
        sdMaterial.setMtlUnit(request.getMtlUnit() != "" ? request.getMtlUnit() : null);
        sdMaterial.setMtlColor(request.getMtlColor() != "" ? request.getMtlColor() : null);
        sdMaterial.setGrossWeight(request.getGrossWeight());
        sdMaterial.setNetWeight(request.getNetWeight());
        sdMaterial.setSysUser(UserIdThread.get().getUserName());
        int count = brandMaterialDefinitionMapper.addSdMaterial(sdMaterial);
        if (count > 0) {
            return ResponseInfo.ok("物料增加成功");
        }else{
            throw new ServiceErrorException("物料增加失败");
        }

        } finally {
            // 检查并释放锁
            String existingValue = (String) redisTemplate.opsForValue().get(lockKey);
            if (lockValue.equals(existingValue)) {
                redisTemplate.delete(lockKey); // 释放锁
            }
        }
    }

    /**
     * 物料资料建档：编辑
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updateSdMaterial(SdMaterialRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        SdMaterial sdMaterial = new SdMaterial();
        if(ObjectUtils.isEmpty(request)){
            throw new ServiceErrorException("参数异常");
        }
        BeanUtils.copyProperties(request, sdMaterial);
        sdMaterial.setCompanyId(companyId);
        int count = brandMaterialDefinitionMapper.updateSdMaterial(sdMaterial);
        if (count > 0) {
            return ResponseInfo.ok("操作成功");
        }else{
            throw new ServiceErrorException("操作失败");
        }
    }

    /**
     * 物料资料建档：删除
     * @param mtlNo
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteMaterialDataFiling(String mtlNo) {
        String companyId = UserIdThread.get().getCompanyId();
//        SdMaterial sdMaterial = brandMaterialDefinitionMapper.getMaterialDataFiling(companyId, mtlNo);
        brandMaterialDefinitionMapper.deleteMaterialDataFiling(companyId, mtlNo);
        return ResponseInfo.ok("操作成功");
    }

    /**
     * 物料资料建档:增加
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo addMaterialDataFiling(SdMaterialRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        SdMaterial sdMaterial = new SdMaterial();
        if(ObjectUtils.isEmpty(request)){
            throw new ServiceErrorException("参数异常");
        }
        sdMaterial.setMtlNo(request.getMtlNo());
        sdMaterial.setCompanyId(companyId);
        sdMaterial.setMtlType(request.getMtlType());
        sdMaterial.setMtlName(request.getMtlName());
        sdMaterial.setMtlSpec(request.getMtlSpec());
        sdMaterial.setMtlUnit(request.getMtlUnit());
        sdMaterial.setMtlColor(request.getMtlColor());
        sdMaterial.setGrossWeight(request.getGrossWeight());
        sdMaterial.setNetWeight(request.getNetWeight());
        int count = brandMaterialDefinitionMapper.addSdMaterial(sdMaterial);
        if (count > 0) {
            return ResponseInfo.ok("操作成功");
        }else{
            throw new ServiceErrorException("操作失败");
        }
    }

    /**
     * 整个品牌删除
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteAllBrandMaterial(String style ) {
        String companyId = UserIdThread.get().getCompanyId();
        int count = brandMaterialDefinitionMapper.deleteBrandMaterial(style, companyId);
        int count2 = brandMaterialDefinitionMapper.deleteAllPackagMaterial(style, companyId);
        int count3 = brandMaterialDefinitionMapper.deleteAllMaterial(style, companyId);
        if(count > 0){
            return ResponseInfo.ok("操作成功");
        }else{
            throw new ServiceErrorException("操作失败");
        }
    }

    /**
     * 生成物料编号:从数据库里面取数据从小到大
     * @param type 物料类型
     * @param num 编码数字部分最初长度
     * @param originalValue 原始编码
     * @return
     */
    public static String generateNewCode(String type, int num ,String originalValue) {
        // 2. 解析编号中的数字部分
        BigInteger numberPart;
        if (originalValue == null) {
            numberPart = BigInteger.ZERO; // 如果没有现有编号，则从0开始
        } else {
            // 假设 code 字段是 "U00018" 类似的格式，我们只需要数字部分
            String code = originalValue;
            String prefix = type; // 假设 MtlType 是前缀
            if (!code.startsWith(prefix)) {
                throw new ServiceErrorException("检索到的代码与预期的前缀不匹配!");
            }
            numberPart = new BigInteger(code.substring(prefix.length()));
        }

        // 3. 递增数字部分
        BigInteger nextNumber = numberPart.add(BigInteger.ONE);

        // 4. 格式化编号
        // 确保使用 nextNumber 而不是未定义的 number
        String formattedNumber = String.format("%0" + Math.max(num, nextNumber.toString().length()) + "d", nextNumber);
        String newCode = type + formattedNumber;
        return newCode;
    }

}

